--
-- Author: yawei.zhu
-- Date: 2018-10-05 11:27:55
--
-- GoddessWishView
--
local GoddessWishRender = import(".renders.GoddessWishRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.GoddessWishScene

local Card_interval = 270

function ClassRef:init()
	-- 设置父亲的透明度传递给孩子
	self._ui.Panel_tlt:setCascadeOpacityEnabled(true) -- 必须设置，不然动画效果不对

	self._ui.Button_close_0:addClickEventListener(function()
		--当前界面若还有BUFF没有领取 则弹出提示
		if not self._goddessMystery and self._goddessInfo.residualTimes and self._goddessInfo.residualTimes > 0 then
			local confirmDialog = display.newConfirmDialog(L("goddesswish_remind"),
            function() -- 确定
                self:closeView()
            end)
			UIHandler:addPopDialog( confirmDialog )
		else
			self:closeView()
		end
	end)

	self._wishCards = {}
	for i = 1, 4 do
		local render = GoddessWishRender.create(self._ui["card_wish/card_"..i])
		render:onBtnClick(function()
			if self._isPlaying then
				display.pushToast(L("lua_code_text_105"))
				return
			end
			if self._goddessInfo.residualTimes <= 0 then
				display.pushToast(L("lua_code_text_419"))
				return
			end
			self._isPlaying = true
			executeFunc(self._onOperate, "onSelectCard", {self._goddessInfo.id, i - 1})
		end)
		self._wishCards[i] = render
	end

	self._mysteryCard = GoddessWishRender.create(self._ui.card_mystery)
	self._mysteryCard:onBtnClick(function()
		if self._isPlaying then
			display.pushToast(L("lua_code_text_105"))
			return
		end
		self._isPlaying = true
		--女神祝福的动画也要播放
		self:showMysteryAni()
		--self:onOpenCardSuccess(index, info)
	end)
end

function ClassRef:updateView(info)
	self._ui.card_wish:setVisible(true)
	self._ui.text_wish:setVisible(true)
	self._ui.Button_close_0:setVisible(true)

	self._goddessInfo = info
	self._ui.tips1:setString(string.format(L("lua_code_text_536"), self._goddessInfo.residualTimes))

	for i = 1, 4 do
		self._wishCards[i]:setData(info.cards[i])
	end
	-- 排列位置
	self:_doLayoutCardPos()
end

-- 排列卡片位置
function ClassRef:_doLayoutCardPos()
	if cc.isDead(self) then return end

	self._isPlaying = false

	-- 找到现在还存在的卡片
	local exists = {}
	for i = 1, 4 do
		local render = self._wishCards[i]
		if render:isVisible() then
			table.insert(exists, render)
		end
	end

	local count = #exists
	if count == 0 then
		if not self._goddessMystery then
			print("Error: 服务器未下发女神祝福神秘奖励！") --@ignore
		else
			self:showCardMystery()
		end
		return
	end

	local midX = self._ui["Panel/card_wish"]:getContentSize().width / 2
	local midCount = (count + 1) / 2
	for i = 1, count do 
		local render = exists[i]
		-- render:setPositionX(midX - (midCount - i) * Card_interval)

		local targetX = midX - (midCount - i) * Card_interval
		local targetY = render:getPositionY()
		local seq = cc.Sequence:create(cc.MoveTo:create(0.5, cc.p(targetX, targetY)))
		render:runAction(seq)
	end

end

-- index 0 - 3
function ClassRef:onOpenCardSuccess(index, info)
	-- 播放特效, 特效播放完会 调整卡牌位置
	index = index + 1
	-- 查找本次抽卡是否有摧毁的卡片
	local destroys = {}
	for i = 1, 4 do
		if i ~= index and info.cards[i].open and not self._goddessInfo.cards[i].open then
			table.insert(destroys, i)
		end
	end

	dump(destroys, "destroys")

	-- 选中卡的特效播放完
	local function onOpenCardAniCallBack()
		if cc.isDead(self) then return end

		local count = #destroys
		if count > 0 then
			self:playCardAmi(destroys[1], handler(self, self._doLayoutCardPos))
			for i = 2, count do
				self:playCardAmi(destroys[i])
			end
		else
			self:_doLayoutCardPos()
		end
	end

	self._goddessInfo = info
	self._ui.tips1:setString(string.format(L("lua_code_text_536"), self._goddessInfo.residualTimes))
	-- 首先播放 选中的卡的特效
	self:playCardAmi(index, onOpenCardAniCallBack)
end

function ClassRef:playCardAmi(index, cb)
	self._wishCards[index]:setVisible(false)
	local posx, posy = 0, 0
	for i = 1, 4 do
		if index == i then
			posx, posy = self._wishCards[i]:getPosition()
			break
		end
	end

	local cardInfo = self._goddessInfo.cards[index]
	local colorType = protobuf.enum_id("pb_goddessbless.CardQuality", cardInfo.quality)
	local bgPath = Res.GoddessWish_EffectBg[colorType]

	local panel = self._ui["Panel/card_wish"]
    panel:removeChildByName( "_refreshAnimationTemp" .. index )
    local amiNodeTemp = cc.CSLoader:createNode( Res.GoddessWishAmi )
    amiNodeTemp:setName( "_refreshAnimationTemp" .. index)
    amiNodeTemp:findChild("Panel/Light1_1"):setTexture(bgPath) -- 更换特效图片
    amiNodeTemp:setPosition( cc.p(posx, posy) )
    panel:addChild( amiNodeTemp )
    amiNodeTemp:getTimeline():gotoFrameAndPlay( 0, false )

    local actions = {}
    table.insert( actions, cc.DelayTime:create( amiNodeTemp:getTimeline():getDuration() / 60 ) )
    table.insert( actions, cc.CallFunc:create( function()
    	amiNodeTemp:removeFromParent()
    	executeFunc(cb)
    end ) )
    table.insert( actions, cc.RemoveSelf:create() )
    amiNodeTemp:runAction( cc.Sequence:create( actions ) )
end

function ClassRef:showMysteryAni()
	local posx, posy = self._mysteryCard:getPosition()
	local colorType = protobuf.enum_id("pb_goddessbless.CardQuality", "orange")
	local bgPath = Res.GoddessWish_EffectBg[colorType]

	local panel = self._ui["Panel"]
	panel:removeChildByName("card_mystery")
	local amiNodeTemp = cc.CSLoader:createNode( Res.GoddessWishAmi )
	amiNodeTemp:setName( "_refreshAnimationMystery")
	amiNodeTemp:findChild("Panel/Light1_1"):setTexture(bgPath) -- 更换特效图片
	amiNodeTemp:setPosition( cc.p(posx, posy) )
	panel:addChild( amiNodeTemp )
	amiNodeTemp:getTimeline():gotoFrameAndPlay( 0, false )

	local actions = {}
	table.insert( actions, cc.DelayTime:create( amiNodeTemp:getTimeline():getDuration() / 60 ) )
	table.insert( actions, cc.CallFunc:create( function()
		amiNodeTemp:removeFromParent()
		self:closeView(false)
	end ) )
	table.insert( actions, cc.RemoveSelf:create() )
	amiNodeTemp:runAction( cc.Sequence:create( actions ) )
end


function ClassRef:showCardMystery()
	self._ui.text_wish:setVisible(false)
	self._ui.name:setString(L("lua_code_text_89"))

	-- 播放一次特效
	self:show()
	scheduler.newCron(function()
		self._mysteryCard:setVisible(true)
		self._ui.text_mystery:setVisible(true)
	end, 0.5)

	local data = {}
	data.id = self._goddessMystery
	data.quality = "orange" -- 惊喜卡
	self._mysteryCard:setData(data)

end

function ClassRef:revertGoddessStatus()
	self._isPlaying = false
end

function ClassRef:onNotifyMysteryReward(cardId)
	self._goddessMystery = cardId
end

return ClassRef
